var express = require('express');
var router = express.Router();

const helper = require('../../util/helper');
const utils = require('../../util/utils');
const userService  = require("../../services/admin/userService");

/**
 * GET /login 登录
 */
router.get('/', (req, res, next) => {
    const user = req.session && req.session.user;
    if (user) {
        res.redirect("/");
    }

    res.render('admin/login', {title: 'Login', msg: "请输入您的用户名和密码"});
});

/**
 * GET /login/exit 注销
 */
router.get('/exit', (req, res, next) => {
    req.session.destroy(function (err) {
        if (err) {
            console.error("--> session destroy failed.err -> ", err);
        }
    });
    res.redirect("/login");
});

/**
 * POST /login 登录
 */
router.post("/", async(req, res, next) => {
    var {username, password, is_remember} = req.body;
    var signInParams = {
        user_name: username.trim(),
        password: password.trim()
    };

    userService.signInByPassword(signInParams, async function (err, user) {
        if (!!err) {
            return res.status(200).json({error: err.errCode, msg: err.message});
        }

        req.session.user = user;

        await helper.setMenus(req, user.id);
        await helper.saveLoginLog(user.id, user.user_name, user.name, utils.clientIpV4(req));

        if (is_remember) {
            res.cookie("login.username", username, {
                maxAge: 1000 * 60 * 60 * 24 * 365 * 10
            });
        }

        res.redirect("/");
    });
});

module.exports = router;
